package com.soloyogame.anitoys.b.web.controller.interceptor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.soloyogame.anitoys.b.web.util.LoginUserHolder;
import com.soloyogame.anitoys.db.commond.Account;
import com.soloyogame.anitoys.db.commond.Business;
import com.soloyogame.anitoys.db.commond.CartInfo;
import com.soloyogame.anitoys.db.commond.Catalog;
import com.soloyogame.anitoys.db.commond.Help;
import com.soloyogame.anitoys.db.commond.News;
import com.soloyogame.anitoys.db.commond.Product;
import com.soloyogame.anitoys.db.commond.SystemSetting;
import com.soloyogame.anitoys.service.BusinessService;
import com.soloyogame.anitoys.service.CatalogService;
import com.soloyogame.anitoys.service.HelpService;
import com.soloyogame.anitoys.service.NewsService;
import com.soloyogame.anitoys.service.SystemSettingService;
import com.soloyogame.anitoys.util.cache.RedisCacheProvider;
import com.soloyogame.anitoys.util.constants.ManageContainer;

/**
 * Created by rj-pc on 2016/4/4.
 */
public class AnitoysInterceptor implements HandlerInterceptor 
{
        private static final Logger LOGGER = LoggerFactory.getLogger(AnitoysInterceptor.class);

        @Autowired
        private BusinessService businessService;
        @Autowired
        private CatalogService catalogService;
        @Autowired
        private NewsService newsService;
        @Autowired
        private HelpService helpService;
        @Autowired
        private SystemSetting systemSetting;
        @Autowired
        private SystemSettingService systemSettingService;
        @Autowired
        private RedisCacheProvider redisCacheProvider;

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            // 加载 商家列表
            List<Business> businessList = loadBusinessList();
            request.setAttribute("businessList", businessList);
            // 加载文章目录
            List<Catalog> newCatalogs = loadCatalogNews();
            request.setAttribute("newsCatalogs", newCatalogs);
            // 加载帮助支持
            List<Help> helpList = loadHelpList();
            request.setAttribute("helpList", helpList);
            systemSetting = systemSettingService.selectOne(new SystemSetting());
            redisCacheProvider.put("systemSetting", JSON.toJSONString(systemSetting));
            //加载购物车信息
            CartInfo cartInfo = getMyCart();
            List<Product> productList = new ArrayList<Product>();
            if (cartInfo != null) {
                productList = cartInfo.getProductList();
            } else {
                cartInfo = new CartInfo();
            }
            request.setAttribute("cartInfo", cartInfo);
            request.setAttribute("productList", productList);
            return true;
        }

        /**
         *
         * postHandle(controller处理过后 会进入此方法)
         *
         * @Title: postHandle
         * @Description:
         * @param @param request
         * @param @param response
         * @param @param handler
         * @param @param modelAndView
         * @param @throws Exception
         * @throws
         */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        }


        private   List<Catalog> loadCatalogNews() 
        {
            List<Catalog> newCatalogs = new ArrayList<Catalog>();
            Serializable serializable;
            try 
            {
                serializable =  redisCacheProvider.get(ManageContainer.CACHE_NEWSCATALOGS);
            } 
            catch (Exception e) 
            {
                serializable = null;
            }
            String nullValue = "null";
            if (serializable == null || serializable.toString().equals(nullValue)) 
            {
                // 查询 文章目录
                Catalog c = new Catalog();
                c.setType("a");
                c.setPid("0");
                c.setShowInNav("y");
                newCatalogs = catalogService.selectList(c);
                if (newCatalogs != null && newCatalogs.size() > 0) 
                {
                    for (int i = 0; i < newCatalogs.size(); i++) 
                    {
                        Catalog catalog = newCatalogs.get(i);
                        //加载此目录下的所有文章列表
                        News news = new News();
                        news.setCatalogID(catalog.getId());
                        news.setStatus("y");
                        List<News> newsList = newsService.selectPlatList(news);
                        catalog.setNews(newsList);
                    }
                }
            } else {
                newCatalogs =  JSON.parseArray(serializable.toString(), Catalog.class);
            }
            redisCacheProvider.put(ManageContainer.CACHE_NEWSCATALOGS, JSON.toJSONString(newCatalogs));
            return newCatalogs;
        }

        /**
         * 加载商家列表
         * @return List<Business>
         */
        private   List<Business> loadBusinessList() 
        {
            Business business = new Business();
            List<Business> businessList = new ArrayList<Business>();
            Serializable serializable;
            try 
            {
                serializable =  redisCacheProvider.get(ManageContainer.CACHE_BUSINESSLIST);
            } 
            catch (Exception e) 
            {
                serializable = null;
            }
            String nullValue = "null";
            if (serializable == null || serializable.toString().equals(nullValue)) 
            {
                // 查询 商家列表
                businessList = businessService.selectList(business);
            } 
            else 
            {
                businessList =  JSON.parseArray(serializable.toString(), Business.class);
            }
            redisCacheProvider.put(ManageContainer.CACHE_BUSINESSLIST, JSON.toJSONString(businessList));
            return businessList;
        }

    /**
     * 帮助支持列表
     * @return List<Help>
     */
    private   List<Help> loadHelpList() 
    {
        List<Help> helpList = new ArrayList<Help>();
        Serializable serializable;
        try 
        {
            serializable =  redisCacheProvider.get(ManageContainer.CACHE_HELPLIST);
        } 
        catch (Exception e) 
        {
            serializable = null;
        }
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) 
        {
            //	帮助支持列表
            Help help = new Help();
            help.setStatus("y");
            helpList = helpService.selectList(help);
        } 
        else 
        {
            helpList =  JSON.parseArray(serializable.toString(), Help.class);
        }
        redisCacheProvider.put(ManageContainer.CACHE_HELPLIST, JSON.toJSONString(helpList));
        return helpList;
    }
    
    protected CartInfo getMyCart() 
    {
        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息
        CartInfo cartInfo = null;
        if (account == null) 
        {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } 
        else 
        {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + account.getId() + "Cart");
        }
        return cartInfo;
    }
}
